/*
 * @Author: MrDotYan 2564217790@qq.com
 * @Date: 2024-08-26 10:41:26
 * @LastEditors: MrDotYan 2564217790@qq.com
 * @LastEditTime: 2024-09-10 19:50:10
 * @FilePath: /webServerAdmin/src/directives/modules/auth.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * v-auth
 * 按钮权限指令
 */
import { RoleSchema } from "@/schema";
import { useUserStore } from "@/stores/modules/user";
import type { Directive, DirectiveBinding } from "vue";

function handlerPermission(arr?: Array<RoleSchema>) {
  return arr?.map(ele => ele.id);
}

const role: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    const userStore = useUserStore();
    const roles = handlerPermission(userStore.userInfo.role ?? []);
    if (value instanceof Array && value.length) {
      const hasPermission = value.every(item => roles?.includes(item));
      if (!hasPermission) el.remove();
    } else {
      if (!roles?.includes(value)) el.remove();
    }
  }
};

export default role;
